<template>
  <div class="new-month-plan">
    <div>
      <div style="margin: 10px 0;display: flex;justify-content: space-between;align-items: center;">
        <div>
          <span v-if="isNewPlan">新建月计划</span>
        </div>
        <div>
          <el-button type="primary" size="mini" @click="backMine">返回</el-button>
          <el-button type="primary" size="mini" @click="publishPlan(1)" v-if="saveFlag">发布计划</el-button>
          <el-button type="primary" size="mini" @click="saveToDraft(0,historyYear)" >保存为草案</el-button>
        </div>
      </div>
      <div>
        <div class="btnCopy space-between">
          <div v-if="isNewPlan">
            <el-select size="mini" style="width: 100px" placeholder="请选择" v-model="historyYear" @change="tChangeSet">
              <el-option v-for="(n,index) in 10" :key="index"
                         :label="currentYear+n-1" :value="currentYear+n-1">
              </el-option>
            </el-select>
            <el-select size="mini" style="width: 100px" placeholder="请选择" v-model="newMonth" @change="tChangeSet">
              <el-option v-for="(n,index) in monthData" :key="index"
                         :label="n" :value="n">
              </el-option>
            </el-select>
          </div>
          <div v-else>
            当前版本:{{currentVersion}}
          </div>
          <el-row>
            <el-button type="primary" plain size="mini" @click="copyBox = true;selectPlanYear()">复制计划到本次</el-button>
            <el-button type="primary" plain size="mini"  @click="downLoadDoc('月销售计划')">模板下载</el-button>
            <el-upload class="upload-demo" action="/front/excelUpload?method=importMonthPlan"
                       :show-file-list="false" :data="dataSetParam" :on-success="handleSuccessWord" accept=".xlsx,.xls"
                       :file-list="fileList" :headers="headersSet">
              <el-button  plain type="primary" size="mini">导入计划</el-button>
            </el-upload>
          </el-row>
        </div>
        <div style="line-height: 30px;">
            月计划总额<span style="font-size:18px;color:#ffc323">{{priceTotal}}</span> 万,月计划总量<span style="font-size:18px;color:#ffc323">{{sellTotal}}</span>万
            上月计划总额<span style="font-size:18px;color:#ffc323">{{priceTotal}}</span> 万,上月计划总量<span style="font-size:18px;color:#ffc323">{{sellTotal}}</span>万
        </div>
        <div class="space-between" style="display: flex;margin-top: 20px">
          <el-form :inline="true" class="demo-form-inline single-form-inline planS" size="mini">
            <el-form-item label="品类">
              <el-select  size="mini" placeholder="请选择" v-model="firstCate" @change="allProduct">
                <el-option v-for="(item,index) in firstCateList" :key="index"
                           :label="item.categoryName" :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select  size="mini" placeholder="请选择" v-model="secondCate" @change="allProduct">
                <el-option v-for="(item,index) in secondCateList" :key="index"
                           :label="item.categoryName" :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品名称">
              <el-input v-model="pName" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item >
              <el-button type="primary" size="mini" @click="getDataMineSet(pName,secondCate=='全部'? firstCate:secondCate)">查询</el-button>
            </el-form-item>
          </el-form>
          <div v-if="selectLook">
            <el-radio-group  size="mini" v-model="isNoPlan" @change="planSelect">
              <el-radio-button label='2'>全部</el-radio-button>
              <el-radio-button label="0">只看有计划</el-radio-button>
              <el-radio-button label="1">只看无计划</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>
      <div style="padding:10px">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(item,index) in draftPlan" :key="index" class="newPlan" v-if="draftPlan">
            <el-card style="width:100%;display:inline-block;margin:10px;cursor: pointer" v-if="hasPlans || item.plan == isNoPlan">
              <div style="font-size:17px; margin-bottom: 8px; min-height: 52px;" @click="productBox = true;checkChart(item.productCode,currentYear)">
                {{item.productName}}
              </div>
              <div class="flex-container space-between">
                <div style="margin:10px 0" @click="productBox = true;checkChart(item.productCode,currentYear)">
                  <el-tag size="mini" v-if="item.productType">{{item.productType}}</el-tag>
                  <el-tag size="mini" v-else="item.productType">空</el-tag>
                  <el-tag size="mini" type="success" v-if="item.categoryName">{{item.categoryName}}</el-tag>
                  <el-tag size="mini" type="success" v-else="item.categoryName">空</el-tag>
                </div>
                <div  style="font-size:16px;">
                  <span>均价:</span><span style="color:red">{{item.guidePrice}}</span><span>元</span>
                </div>
              </div>
              <div class="flex-container space-between" style="line-height:22px" >
                <div  style="font-size: 12px">
                  <span>计划销额:</span>
                  <span style="font-size:21px;color:#8e71c7">{{(item.guidePrice * item.planSalesNumber) | formatSum}}</span>
                  <span>万元</span>
                </div>
                <div style="font-size:12px;line-height:30px">
                  <span>计划销量:&nbsp;</span>
                  <el-input  class="numInput" type="number" :min="0" v-model="item.planSalesNumber" style="width:60px" size="mini" placeholder=""></el-input>&nbsp;
                  <span>&nbsp;&nbsp;件</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog title="导入月计划" :visible.sync="copyBox" width="35%">
      <div class="copySelect">
        <span>选择计划版本：</span>
        <el-select size="mini" style="width: 100px" placeholder="请选择" v-model="importYear" @change="selectPlanYear">
          <el-option v-for="(n,index) in allPlanYear" :key="index"
                     :label="n" :value="n">
          </el-option>
        </el-select>
        <el-select size="mini" style="" placeholder="请选择计划" v-model="versionSelect">
          <el-option v-for="(v,index) in versionList" :key="index" :label="v.dateTime + v.draftName"
                     :value="v.draftStatus +','+ v.dateTime">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="copyBox = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="copySurePlan(versionSelect)" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="proName" :visible.sync="productBox" width="45%">
      <div class="">
        <el-select size="mini" style="width: 100px" placeholder="请选择" v-model="monthYear" @change="checkChart(proCode,monthYear)">
          <el-option v-for="(n,index) in 10" :key="index"
                     :label="currentYear-n+1" :value="currentYear-n+1">
          </el-option>
        </el-select>
        <div id="saleSummaryCharts" style="height: 300px;width:100%;margin:10px"></div>
      </div>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="draftVisible" width="30%">
      <span>当月已有草案，是否覆盖？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="draftVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveToDraft(1,historyYear)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import * as opreate from 'api/getData'
  import { downLoadDoc } from 'utils/mUtils'

  export default {
    name: "new-month-plan",
    data(){
      return{
        draftVisible:false,
        historyYear: new Date().getFullYear(),
        newMonth: new Date().format('MM'),
        draftPlan: [],
        getProductsBySelectiveData: '',
        currentYear:new Date().getFullYear(),
        priceTotal: 0,
        sellTotal: 0,
        firstCate:'全部',
        firstCateList:[],
        secondCate:'全部',
        secondCateList:[],
        pName:undefined,
        copyBox:false,
        importYear:'',
        versionSelect:'',
        allPlanYear:[],
        versionList:[],
        mainchart:'',
        proName:'',
        proCode:'',
        productBox:false,
        monthYear:new Date().getFullYear(),
        selectLook:false,
        isNoPlan:2,
        isNewPlan:true,
        draftId:'',
        currentVersion:'',
        saveFlag:false,
        hasPlan:0,
        hasPlans:true,
        headersSet: {
          dipsToken: sessionStorage.getItem("tokenName")
        },
        dataSetParam:{
          type: 'Document',
          userId:''
        },
        monthData:['01','02','03','04','05','06','07','08','09','10','11','12'],
        fileList:[],
        paramUrlSet: {}
      }
    },
    mounted(){
      let mineSetInfo = JSON.parse(sessionStorage.getItem('userData')) || {}
      this.paramUrlSet = this.$route.params || {}
      if(this.paramUrlSet.draftStatus){
        this.allYearPlanDetails(this.paramUrlSet.monthPlan)
        this.dataSetParam.userId = `${this.paramUrlSet.monthPlan};${mineSetInfo.phone}`
        this.selectLook = true
        this.isNewPlan = false
      }else {
        this.getDataMineSet()
        this.dataSetParam.userId = `${this.historyYear}-${this.newMonth};${mineSetInfo.phone}`
      }
      this.getCategory()
      this.getSecondCategory()
    },
    methods:{
      tChangeSet(){
        let mineSetInfo = JSON.parse(sessionStorage.getItem('userData')) || {}
        this.dataSetParam.userId = `${this.historyYear}-${this.newMonth};${mineSetInfo.phone}`
      },
      handleSuccessWord(res,file){
        if('200' == res.code){
          switch (res.number) {
            case "-4":
              this.$message.error('导入计划为空，请重试')
              break
            case "-3":
              this.$message.error('导入计划失败，已有计划')
              break
            case "-1":
              this.$message.error('导入计划失败，已有草案')
              break
            case "-2":
              this.$message.error('导入计划失败，请重试')
              break
            default:
              this.$message.success('成功导入计划，失败条数' + res.number + '条');
              break
          }
        }else {
          this.$message.error('导入计划失败，请重试')
        }
      },
      downLoadDoc(name){
        downLoadDoc(name)
      },
      getDataMineSet(productName,categoryId){ // 新建计划
        opreate.getProdBySelect({
          productName: productName == ''? null : productName,
          categoryId: categoryId == '全部'? null : categoryId
        }).then(res => {
          this.draftPlan = res.data
        })
      },
      planSelect(newVal){
        this.hasPlans = '2' == newVal
      },
      allYearPlanDetails(monthPlanTime,productName,codeSet) { // 获取某年的计划
        this.selectLook = true
        opreate.getMonthPlan({
          monthPlanTime,
          productName,
          categoryId: '全部' == codeSet  ? null : codeSet,
          draftStatus: this.paramUrlSet.draftStatus,
          isPlan: '2' == this.isNoPlan ? null : this.isNoPlan
        }).then(res => {
          let { draftStatus, list, draftName, draftId } = res.data || {}
          this.saveFlag = '0' == draftStatus
          this.draftPlan = list || []
          this.currentVersion = draftName
          this.draftId = draftId
        })
      },
      checkChart(productCode,dateTime){
        this.proName = productCode + "  " + dateTime + "销售计划"
        this.proCode = productCode
        opreate.getSaleMonthData({ productCode, dateTime }).then(res => {
          let myChart = this.$echarts.init(document.getElementById('saleSummaryCharts'));
          let [ mainChart = [] ] = res.data || []
          this.mainchart = mainChart
          let option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                crossStyle: {
                  color: '#999'
                }
              },
              formatter:'{b}<br />{a0}: {c0}万件<br />{a1}: {c1}%<br />{a2}: {c2}万元<br />{a3}: {c3}%'
            },
            legend: {
              data:['销售量','销量环比','销售额','销额环比']
            },
            xAxis: [
              {
                type: 'category',
                data: this.mainchart.map(item => item.dateTime)
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '销售量/销售额（万）',
                axisLabel: {
                  formatter: '{value} '
                }
              },
              {
                type: 'value',
                name: '环比',
                axisLabel: {
                  formatter: '{value} '
                }
              }
            ],
            series: [
              {
                name:'销售量',
                type:'bar',
                yAxisIndex: 0,
                itemStyle: {
                  color: '#9c96e7'
                },
                data:this.mainchart.map(item => item.actualSalesCount/10000)
              },
              {
                name:'销量环比',
                type:'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#9c96e7'
                },
                data:this.mainchart.map(item => item.actualSalesCountRingRatio)
              },
              {
                name:'销售额',
                type:'bar',
                yAxisIndex: 0,
                itemStyle: {
                  color: '#64bef5'
                },
                data:this.mainchart.map(item => item.actualSalesAmount/10000)
              },
              {
                name:'销额环比',
                type:'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#64bef5'
                },
                data:this.mainchart.map(item => item.actualSalesAmountRingRatio)
              },
            ]
          };
          myChart.setOption(option); // 使用刚指定的配置项和数据显示图表
        })
      },
      saveToDraft(isInsert,year){
        this.draftVisible = false
        let newArrSet = this.draftPlan.reduce((rootSet, item) => {
          if(item.planSalesNumber.toString().trim() !== '0' && item.planSalesNumber.toString().trim() !== ''){
            rootSet.push(item)
          }
          return rootSet
        }, [])
        //判断新建草案OR修改
        if(this.isNewPlan || !this.saveFlag){
          opreate.createMonthDraft({
            monthPlanTimme: this.historyYear + '-' + this.newMonth,
            list: newArrSet,
            isInsert: isInsert
          }).then(res => {
            if(res.data == '0'){
              this.$message.error('保存失败，已有月计划');
            }else if(res.data == '1'){
              this.draftVisible = true
            }else if(res.data == '2'){
              this.$message.success('保存草案成功');
            }else {
              this.$message.error('操作失败');
            }
          })
        }else {
          this.publishPlan(0)
        }
      },
      copySurePlan(monPlan){
        if(monPlan){
          let [ draftStatus, monthPlanTime ] = monPlan.split(',')
          opreate.getMonthPlan({ draftStatus, monthPlanTime }).then(res => {
            if('200' == res.code){
              this.draftPlan = res.data.list || []
            }else {
              this.draftPlan = []
              this.$message.error('信息查询失败，请稍后再试')
            }
            this.selectLook = true
            this.secondCate = ''
            this.firstCate = ''
            this.pName = ''
          })
        }
        this.copyBox = false
      },
      backMine(){
        this.$router.back(-1)
      },
      allProduct(newVal){
        this.getSecondCategory()
        this.selectLook
          ? this.allYearPlanDetails(this.historyYear,this.pName,newVal)
          : this.getDataMineSet(this.pName,newVal)
      },
      publishPlan(isUpdateToPlan){
        let msgSet = isUpdateToPlan == '0'? '草案保存成功':'发布计划成功'
        let newArrSet = this.draftPlan.reduce((rootSet,item) => {
          if(item.planSalesNumber.toString().trim() !== '0' && item.planSalesNumber.toString().trim() !== ''){
            rootSet.push(item)
          }
          return rootSet
        },[])
        opreate.updateDraftByDraftId({
          draftId:this.draftId,
          isUpdateToPlan:isUpdateToPlan,
          monthPlanTimme: this.paramUrlSet.monthPlan ? this.paramUrlSet.monthPlan : this.historyYear + '-' + this.newMonth,
          list: newArrSet
        }).then(res => {
          if(res.code == '200'){
            this.$message.success(msgSet);
          }else {
            this.$message.error('操作失败，稍后再试');
          }
        })
      },
      selectPlanYear(yearPlanTime){
        yearPlanTime ? '' : this.importYear = ''
        this.versionSelect = ''
        opreate.getMonthPlanByYear({ yearPlanTime }).then(res => {
          let { listYear = [], li = [] } = res.data || {}
          this.allPlanYear = listYear || []
          this.versionList = (li && li.length > 0) ? li[0].list : []
        })
      },
      getCategory(){
        opreate.getFirstCateSet({}).then(res => {
          this.firstCateList = res.data
        })
      },
      getSecondCategory(){
        opreate.getSecondCateSet({
          categoryId:this.firstCate == '全部' ? undefined : this.firstCate
        }).then(res => {
          this.secondCateList = res.data
        })
      }
    },
    watch: {
      draftPlan:{
        handler(newVal,oldVal){
          let price = 0,sell = 0
          for (let idx in newVal){
            price += (newVal[idx].guidePrice * newVal[idx].planSalesNumber)
            sell += Number(newVal[idx].planSalesNumber)
          }
          this.priceTotal = price/10000
          this.sellTotal = sell/10000
        },
        deep:true
      },
      firstCate(newVal){
        this.secondCate = '全部'
      }
    },
  }
</script>

<style scoped>
  .checkHis{
    font-size: 12px;
    color: #409EFF;
  }
  .btnCopy{
    display: flex;
  }
  .copySelect{
    margin-top: 30px;
    margin-bottom: 50px;
  }
  .upload-demo{
    display: inline-block;
    margin-left: 8px;
  }
</style>
